class SnakeGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.gridSize = 20;
        this.tileCount = this.canvas.width / this.gridSize;
        
        // 游戏状态
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.highScore = localStorage.getItem('snakeHighScore') || 0;
        
        // 蛇的初始状态
        this.snake = [
            {x: 10, y: 10}
        ];
        this.dx = 0;
        this.dy = 0;
        this.nextDx = 0;
        this.nextDy = 0;
        
        // 食物
        this.food = this.generateFood();
        
        // 游戏速度
        this.baseSpeed = 150;
        this.gameSpeed = this.baseSpeed;
        this.speedLevel = 3; // 默认中等速度
        this.gameLoop = null;
        
        // 粒子效果系统
        this.particles = [];
        this.particleColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8'];
        
        // DOM元素
        this.scoreElement = document.getElementById('score');
        this.highScoreElement = document.getElementById('highScore');
        this.gameOverlay = document.getElementById('gameOverlay');
        this.overlayTitle = document.getElementById('overlayTitle');
        this.overlayMessage = document.getElementById('overlayMessage');
        this.finalScoreElement = document.getElementById('finalScore');
        
        // 初始化
        this.init();
    }
    
    init() {
        this.updateHighScore();
        this.setupEventListeners();
        this.draw();
    }
    
    setupEventListeners() {
        // 键盘控制
        document.addEventListener('keydown', (e) => {
            this.handleKeyPress(e);
        });
        
        // 按钮控制
        document.getElementById('startBtn').addEventListener('click', () => {
            this.startGame();
        });
        
        document.getElementById('pauseBtn').addEventListener('click', () => {
            this.togglePause();
        });
        
        document.getElementById('restartBtn').addEventListener('click', () => {
            this.restartGame();
        });
        
        // 速度控制
        const speedSlider = document.getElementById('speedSlider');
        const speedValue = document.getElementById('speedValue');
        
        speedSlider.addEventListener('input', (e) => {
            this.speedLevel = parseInt(e.target.value);
            this.updateSpeed();
            this.updateSpeedLabel();
        });
        
        // 初始化速度标签
        this.updateSpeedLabel();
        
        // 触摸控制（移动端）
        let touchStartX = 0;
        let touchStartY = 0;
        
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        });
        
        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            const touchEndX = e.changedTouches[0].clientX;
            const touchEndY = e.changedTouches[0].clientY;
            
            const deltaX = touchEndX - touchStartX;
            const deltaY = touchEndY - touchStartY;
            
            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                // 水平滑动
                if (deltaX > 0 && this.dy !== -1) {
                    this.nextDx = 1;
                    this.nextDy = 0;
                } else if (deltaX < 0 && this.dy !== 1) {
                    this.nextDx = -1;
                    this.nextDy = 0;
                }
            } else {
                // 垂直滑动
                if (deltaY > 0 && this.dx !== -1) {
                    this.nextDx = 0;
                    this.nextDy = 1;
                } else if (deltaY < 0 && this.dx !== 1) {
                    this.nextDx = 0;
                    this.nextDy = -1;
                }
            }
        });
    }
    
    handleKeyPress(e) {
        switch(e.key) {
            case 'ArrowUp':
            case 'w':
            case 'W':
                if (this.gameRunning && !this.gamePaused && this.dy !== 1) {
                    this.nextDx = 0;
                    this.nextDy = -1;
                }
                break;
            case 'ArrowDown':
            case 's':
            case 'S':
                if (this.gameRunning && !this.gamePaused && this.dy !== -1) {
                    this.nextDx = 0;
                    this.nextDy = 1;
                }
                break;
            case 'ArrowLeft':
            case 'a':
            case 'A':
                if (this.gameRunning && !this.gamePaused && this.dx !== 1) {
                    this.nextDx = -1;
                    this.nextDy = 0;
                }
                break;
            case 'ArrowRight':
            case 'd':
            case 'D':
                if (this.gameRunning && !this.gamePaused && this.dx !== -1) {
                    this.nextDx = 1;
                    this.nextDy = 0;
                }
                break;
            case ' ':
                e.preventDefault();
                if (!this.gameRunning) {
                    this.startGame();
                } else {
                    this.togglePause();
                }
                break;
        }
    }
    
    startGame() {
        if (this.gameRunning) return;
        
        this.gameRunning = true;
        this.gamePaused = false;
        this.score = 0;
        this.updateScore();
        
        // 重置蛇的位置和方向
        this.snake = [{x: 10, y: 10}];
        this.dx = 0;
        this.dy = 0;
        this.nextDx = 0;
        this.nextDy = 0;
        
        // 生成新食物
        this.food = this.generateFood();
        
        // 完全重置游戏速度到用户设置的水平
        this.resetSpeed();
        
        // 开始游戏循环
        this.gameLoop = setInterval(() => {
            this.update();
            this.draw();
        }, this.gameSpeed);
        
        // 更新按钮状态
        document.getElementById('startBtn').textContent = '游戏中...';
        document.getElementById('startBtn').disabled = true;
        document.getElementById('pauseBtn').disabled = false;
    }
    
    togglePause() {
        if (!this.gameRunning) return;
        
        this.gamePaused = !this.gamePaused;
        
        if (this.gamePaused) {
            clearInterval(this.gameLoop);
            document.getElementById('pauseBtn').textContent = '继续';
        } else {
            this.gameLoop = setInterval(() => {
                this.update();
                this.draw();
            }, this.gameSpeed);
            document.getElementById('pauseBtn').textContent = '暂停';
        }
    }
    
    restartGame() {
        this.hideGameOver();
        this.startGame();
    }
    
    update() {
        if (this.gamePaused) return;
        
        // 更新粒子
        this.updateParticles();
        
        // 更新蛇的方向
        this.dx = this.nextDx;
        this.dy = this.nextDy;
        
        // 如果蛇没有移动，不更新
        if (this.dx === 0 && this.dy === 0) return;
        
        // 移动蛇头
        const head = {x: this.snake[0].x + this.dx, y: this.snake[0].y + this.dy};
        
        // 检查边界碰撞
        if (head.x < 0 || head.x >= this.tileCount || head.y < 0 || head.y >= this.tileCount) {
            this.gameOver();
            return;
        }
        
        // 检查自身碰撞
        for (let i = 0; i < this.snake.length; i++) {
            if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
                this.gameOver();
                return;
            }
        }
        
        // 添加新头部
        this.snake.unshift(head);
        
        // 检查是否吃到食物
        if (head.x === this.food.x && head.y === this.food.y) {
            this.score += 10;
            this.updateScore();
            
            // 创建粒子效果
            this.createParticles(this.food.x * this.gridSize + this.gridSize / 2, 
                               this.food.y * this.gridSize + this.gridSize / 2);
            
            // 添加震动效果
            this.addShakeEffect();
            
            this.food = this.generateFood();
            
            // 增加游戏速度（基于用户设置的速度）
            if (this.score % 50 === 0) {
                // 基于用户设置的速度等级来计算动态增加的速度
                const speedMultipliers = {
                    1: 2.0,  // 很慢
                    2: 1.5,  // 较慢
                    3: 1.0,  // 中等
                    4: 0.7,  // 较快
                    5: 0.5   // 很快
                };
                
                // 计算当前应该的速度（基于分数和用户设置）
                const baseSpeedForLevel = Math.round(this.baseSpeed * speedMultipliers[this.speedLevel]);
                const speedIncrease = Math.floor(this.score / 50) * 10; // 每50分增加10ms
                this.gameSpeed = Math.max(baseSpeedForLevel * 0.3, baseSpeedForLevel - speedIncrease);
                
                clearInterval(this.gameLoop);
                this.gameLoop = setInterval(() => {
                    this.update();
                    this.draw();
                }, this.gameSpeed);
            }
        } else {
            // 如果没有吃到食物，移除尾部
            this.snake.pop();
        }
    }
    
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#f8f9fa';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格
        this.drawGrid();
        
        // 绘制粒子
        this.drawParticles();
        
        // 绘制蛇
        this.drawSnake();
        
        // 绘制食物
        this.drawFood();
    }
    
    drawGrid() {
        this.ctx.strokeStyle = '#e9ecef';
        this.ctx.lineWidth = 1;
        
        for (let i = 0; i <= this.tileCount; i++) {
            // 垂直线
            this.ctx.beginPath();
            this.ctx.moveTo(i * this.gridSize, 0);
            this.ctx.lineTo(i * this.gridSize, this.canvas.height);
            this.ctx.stroke();
            
            // 水平线
            this.ctx.beginPath();
            this.ctx.moveTo(0, i * this.gridSize);
            this.ctx.lineTo(this.canvas.width, i * this.gridSize);
            this.ctx.stroke();
        }
    }
    
    drawSnake() {
        this.snake.forEach((segment, index) => {
            if (index === 0) {
                // 蛇头
                this.ctx.fillStyle = '#2ecc71';
                this.ctx.fillRect(
                    segment.x * this.gridSize + 2,
                    segment.y * this.gridSize + 2,
                    this.gridSize - 4,
                    this.gridSize - 4
                );
                
                // 蛇头边框
                this.ctx.strokeStyle = '#27ae60';
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(
                    segment.x * this.gridSize + 2,
                    segment.y * this.gridSize + 2,
                    this.gridSize - 4,
                    this.gridSize - 4
                );
                
                // 眼睛
                this.ctx.fillStyle = '#fff';
                this.ctx.fillRect(
                    segment.x * this.gridSize + 6,
                    segment.y * this.gridSize + 6,
                    3,
                    3
                );
                this.ctx.fillRect(
                    segment.x * this.gridSize + 11,
                    segment.y * this.gridSize + 6,
                    3,
                    3
                );
            } else {
                // 蛇身
                this.ctx.fillStyle = '#27ae60';
                this.ctx.fillRect(
                    segment.x * this.gridSize + 1,
                    segment.y * this.gridSize + 1,
                    this.gridSize - 2,
                    this.gridSize - 2
                );
            }
        });
    }
    
    drawFood() {
        // 食物渐变效果
        const gradient = this.ctx.createRadialGradient(
            this.food.x * this.gridSize + this.gridSize / 2,
            this.food.y * this.gridSize + this.gridSize / 2,
            0,
            this.food.x * this.gridSize + this.gridSize / 2,
            this.food.y * this.gridSize + this.gridSize / 2,
            this.gridSize / 2
        );
        gradient.addColorStop(0, '#e74c3c');
        gradient.addColorStop(1, '#c0392b');
        
        this.ctx.fillStyle = gradient;
        this.ctx.beginPath();
        this.ctx.arc(
            this.food.x * this.gridSize + this.gridSize / 2,
            this.food.y * this.gridSize + this.gridSize / 2,
            this.gridSize / 2 - 2,
            0,
            2 * Math.PI
        );
        this.ctx.fill();
        
        // 食物高光
        this.ctx.fillStyle = '#fff';
        this.ctx.beginPath();
        this.ctx.arc(
            this.food.x * this.gridSize + this.gridSize / 2 - 3,
            this.food.y * this.gridSize + this.gridSize / 2 - 3,
            2,
            0,
            2 * Math.PI
        );
        this.ctx.fill();
    }
    
    generateFood() {
        let food;
        do {
            food = {
                x: Math.floor(Math.random() * this.tileCount),
                y: Math.floor(Math.random() * this.tileCount)
            };
        } while (this.snake.some(segment => segment.x === food.x && segment.y === food.y));
        
        return food;
    }
    
    updateScore() {
        this.scoreElement.textContent = this.score;
        
        if (this.score > this.highScore) {
            this.highScore = this.score;
            this.updateHighScore();
            localStorage.setItem('snakeHighScore', this.highScore);
        }
    }
    
    updateHighScore() {
        this.highScoreElement.textContent = this.highScore;
    }
    
    gameOver() {
        this.gameRunning = false;
        clearInterval(this.gameLoop);
        
        this.finalScoreElement.textContent = this.score;
        this.showGameOver();
        
        // 重置按钮状态
        document.getElementById('startBtn').textContent = '开始游戏';
        document.getElementById('startBtn').disabled = false;
        document.getElementById('pauseBtn').textContent = '暂停';
        document.getElementById('pauseBtn').disabled = true;
    }
    
    showGameOver() {
        this.gameOverlay.style.display = 'flex';
        this.gameOverlay.classList.add('show');
    }
    
    hideGameOver() {
        this.gameOverlay.style.display = 'none';
        this.gameOverlay.classList.remove('show');
    }
    
    updateSpeed() {
        // 根据速度等级计算游戏速度
        const speedMultipliers = {
            1: 2.0,  // 很慢
            2: 1.5,  // 较慢
            3: 1.0,  // 中等
            4: 0.7,  // 较快
            5: 0.5   // 很快
        };
        
        this.gameSpeed = Math.round(this.baseSpeed * speedMultipliers[this.speedLevel]);
        
        // 如果游戏正在运行且未暂停，重新设置游戏循环
        if (this.gameRunning && !this.gamePaused) {
            clearInterval(this.gameLoop);
            this.gameLoop = setInterval(() => {
                this.update();
                this.draw();
            }, this.gameSpeed);
        }
    }
    
    updateSpeedLabel() {
        const speedLabels = {
            1: '很慢',
            2: '较慢',
            3: '中等',
            4: '较快',
            5: '很快'
        };
        
        document.getElementById('speedValue').textContent = speedLabels[this.speedLevel];
    }
    
    resetSpeed() {
        // 完全重置游戏速度到用户设置的水平
        const speedMultipliers = {
            1: 2.0,  // 很慢
            2: 1.5,  // 较慢
            3: 1.0,  // 中等
            4: 0.7,  // 较快
            5: 0.5   // 很快
        };
        
        this.gameSpeed = Math.round(this.baseSpeed * speedMultipliers[this.speedLevel]);
    }
    
    createParticles(x, y) {
        // 在指定位置创建粒子效果
        const particleCount = 8 + Math.floor(Math.random() * 5); // 8-12个粒子
        
        for (let i = 0; i < particleCount; i++) {
            const particle = {
                x: x,
                y: y,
                vx: (Math.random() - 0.5) * 8, // 随机水平速度
                vy: (Math.random() - 0.5) * 8, // 随机垂直速度
                size: Math.random() * 4 + 2,   // 随机大小
                color: this.particleColors[Math.floor(Math.random() * this.particleColors.length)],
                life: 1.0,                     // 生命值
                decay: Math.random() * 0.02 + 0.01 // 衰减速度
            };
            
            this.particles.push(particle);
        }
    }
    
    updateParticles() {
        // 更新所有粒子
        for (let i = this.particles.length - 1; i >= 0; i--) {
            const particle = this.particles[i];
            
            // 更新位置
            particle.x += particle.vx;
            particle.y += particle.vy;
            
            // 添加重力效果
            particle.vy += 0.1;
            
            // 减少生命值
            particle.life -= particle.decay;
            
            // 如果粒子生命值耗尽，移除它
            if (particle.life <= 0) {
                this.particles.splice(i, 1);
            }
        }
    }
    
    drawParticles() {
        // 绘制所有粒子
        this.particles.forEach(particle => {
            this.ctx.save();
            
            // 设置透明度
            this.ctx.globalAlpha = particle.life;
            
            // 创建径向渐变
            const gradient = this.ctx.createRadialGradient(
                particle.x, particle.y, 0,
                particle.x, particle.y, particle.size
            );
            gradient.addColorStop(0, particle.color);
            gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
            
            this.ctx.fillStyle = gradient;
            this.ctx.beginPath();
            this.ctx.arc(particle.x, particle.y, particle.size, 0, 2 * Math.PI);
            this.ctx.fill();
            
            this.ctx.restore();
        });
    }
    
    addShakeEffect() {
        const gameContainer = document.querySelector('.game-container');
        gameContainer.classList.add('shake');
        
        // 移除震动效果类
        setTimeout(() => {
            gameContainer.classList.remove('shake');
        }, 300);
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    new SnakeGame();
}); 